import 'dart:math';
import 'package:flutter/material.dart';

class CaptchaWidget extends StatefulWidget {
  final void Function(String) onCaptchaGenerated;
  final Color backgroundColor;
  final Color textColor;

  const CaptchaWidget({
    super.key,
    required this.onCaptchaGenerated,
    this.backgroundColor = Colors.white, // 默认白色背景
    this.textColor = Colors.deepPurple, // 默认深紫色文字
  });

  @override
  State<CaptchaWidget> createState() => _CaptchaWidgetState();
}

class _CaptchaWidgetState extends State<CaptchaWidget> {
  late String _captchaText;
  final Random _random = Random();

  @override
  void initState() {
    super.initState();
    _generateCaptcha();
  }

  void _generateCaptcha() {
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
    _captchaText =
        List.generate(4, (index) => chars[_random.nextInt(chars.length)])
            .join();
    widget.onCaptchaGenerated(_captchaText);
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      elevation: 2,
      borderRadius: BorderRadius.circular(8),
      child: InkWell(
        borderRadius: BorderRadius.circular(8),
        onTap: () {
          setState(() {
            _generateCaptcha();
          });
        },
        child: Container(
          width: 120, // 增加宽度
          height: 48, // 增加高度以匹配输入框
          decoration: BoxDecoration(
            color: widget.backgroundColor,
            borderRadius: BorderRadius.circular(8),
          ),
          child: Stack(
            children: [
              CustomPaint(
                size: const Size(120, 48),
                painter: CaptchaPainter(
                  _captchaText,
                  textColor: widget.textColor,
                ),
              ),
              Positioned(
                right: 4,
                bottom: 4,
                child: Icon(
                  Icons.refresh,
                  size: 16,
                  color: widget.textColor.withOpacity(0.5),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

class CaptchaPainter extends CustomPainter {
  final String text;
  final Color textColor;
  final Random random = Random();

  CaptchaPainter(this.text, {required this.textColor});

  @override
  void paint(Canvas canvas, Size size) {
    // 绘制干扰线
    final paint = Paint()
      ..color = textColor.withOpacity(0.2)
      ..strokeWidth = 1.0
      ..style = PaintingStyle.stroke;

    for (var i = 0; i < 8; i++) {
      // 增加干扰线数量
      final startX = random.nextDouble() * size.width;
      final startY = random.nextDouble() * size.height;
      final endX = random.nextDouble() * size.width;
      final endY = random.nextDouble() * size.height;

      // 使用贝塞尔曲线绘制干扰线
      final path = Path();
      path.moveTo(startX, startY);
      final controlX = (startX + endX) / 2 + (random.nextDouble() * 20 - 10);
      final controlY = (startY + endY) / 2 + (random.nextDouble() * 20 - 10);
      path.quadraticBezierTo(controlX, controlY, endX, endY);
      canvas.drawPath(path, paint);
    }

    // 绘制文字
    final textStyle = TextStyle(
      color: textColor,
      fontSize: 28, // 增大字体
      fontWeight: FontWeight.bold,
      letterSpacing: 2, // 添加字间距
    );

    // 为每个字符单独绘制
    for (var i = 0; i < text.length; i++) {
      final charSpan = TextSpan(
        text: text[i],
        style: textStyle,
      );
      final charPainter = TextPainter(
        text: charSpan,
        textDirection: TextDirection.ltr,
      );
      charPainter.layout();

      canvas.save();
      // 调整字符位置计算
      final charX =
          size.width * (i + 1) / (text.length + 1) - charPainter.width / 2;
      final charY = (size.height - charPainter.height) / 2 +
          (random.nextDouble() * 6 - 3);
      canvas.translate(charX, charY);
      canvas.rotate((random.nextDouble() * 0.4 - 0.2)); // 增加旋转角度
      charPainter.paint(canvas, Offset.zero);
      canvas.restore();
    }
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => true;
}
